//
//  YWAssetCheckDBManager.m
//  maintain
//
//  Created by 烟雨云渊 on 16/10/27.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDBTool.h"
#import "YWAssetCheckDBManager.h"
#import "YWAssetCheckRecord.h"
#import "YWAssetCheckRecordDetails.h"
#import "YWReply.h"
#import "YWBuilding.h"
#import "YWApartment.h"
#import "YWFloor.h"
#import "YWLocation.h"
#import "YWHandler.h"
#import "YWEquipmentType.h"
#import "YWReplyDBManager.h"
#import "YWCommonTool.h"
#import "YWEquipmentManager.h"

@implementation YWAssetCheckDBManager
YWSingletonM(Manager)

- (FMDatabase*)fmdb
{
    return [[YWDBTool shareDBTool] fmdb];
}
- (FMDatabaseQueue*)dbQeue
{
    return [[YWDBTool shareDBTool] dbQeue];
}

- (void)createAllAssetCheckTables{
    [self createAssetCheckTable];
    [self createAssetCheckDetailTable];
}

- (BOOL)createAssetCheckTable{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'assetCheck' (checkRecordId integer,buildingId varchar,apartmentId integer,floorId integer,locationId integer,createTime timestamp,updateTime timestamp,creatorId integer,checkResult integer,note varchar,status integer);";
    return [[self fmdb] executeUpdate:sql];
}

- (BOOL)updateAssetCheckWithArray:(NSArray*)checkArray
{
    if (checkArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockAssetCheckArray = checkArray;
//    __block NSMutableArray* replysArray = [NSMutableArray array];
    __block NSMutableArray* assetDetailArray = [NSMutableArray array];
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockAssetCheckArray enumerateObjectsUsingBlock:^(YWAssetCheckRecord* _Nonnull checkRecord, NSUInteger idx, BOOL* _Nonnull stop) {
            //sql = @"DELETE FROM 'reply' WHERE relationId=?";
            //[db executeUpdate:sql, @(checkRecord.checkRecordId)];
//            if (checkRecord.replies) {
//                [checkRecord.replies enumerateObjectsUsingBlock:^(YWReply* _Nonnull reply, NSUInteger idx, BOOL* _Nonnull stop) {
//                    reply.relationId = checkRecord.checkRecordId;
//                    reply.relationType = YWReplyRelationTypeAssetCheckRecord;
//                }];
//                [replysArray addObjectsFromArray:checkRecord.replies];
//            }
            
            [checkRecord.recordDetails enumerateObjectsUsingBlock:^(YWAssetCheckRecordDetails* _Nonnull checkRecordDetail, NSUInteger idx, BOOL* _Nonnull stop) {
                checkRecordDetail.checkRecordId = checkRecord.checkRecordId;
            }];
            [assetDetailArray addObjectsFromArray:checkRecord.recordDetails];
            
            sql = @"SELECT * FROM 'assetCheck' WHERE checkRecordId=?;";
            FMResultSet* set = [db executeQuery:sql, @(checkRecord.checkRecordId)];
            if ([set next]) {
                sql = @"UPDATE 'assetCheck' SET buildingId =?,apartmentId =?,floorId =?,locationId =?,createTime =?,updateTime =?,creatorId =?,checkResult =?,note =?,status =?WHERE checkRecordId =?;";
                executeResult = [db executeUpdate:sql, checkRecord.building.buildingId,@(checkRecord.apartment.apartmentId),@(checkRecord.floor.floorId),@(checkRecord.location.locationId),@(checkRecord.createTime),@(checkRecord.updateTime),@(checkRecord.creator.uniqueId),@(checkRecord.checkResult),checkRecord.note,@(checkRecord.status),@(checkRecord.checkRecordId)];
            }
            else {
                sql = @"INSERT INTO 'assetCheck' (checkRecordId,buildingId,apartmentId,floorId,locationId,createTime,updateTime,creatorId,checkResult,note,status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
                executeResult = [db executeUpdate:sql,@(checkRecord.checkRecordId), checkRecord.building.buildingId,@(checkRecord.apartment.apartmentId),@(checkRecord.floor.floorId),@(checkRecord.location.locationId),@(checkRecord.createTime),@(checkRecord.updateTime),@(checkRecord.creator.uniqueId),@(checkRecord.checkResult),checkRecord.note,@(checkRecord.status)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
//    [[YWReplyDBManager shareManager] updateReplyWithReplyArray:replysArray];
    //更新清点明细表
    [self updateAssetCheckDetailWithArray:assetDetailArray];
    return executeResult;
}

- (NSArray*)assetCheckWithPage:(NSInteger)page locationId:(NSInteger)locationId
{
    __block NSMutableArray* blockAssetArray = [NSMutableArray array];
    __block NSInteger showCount = page * 10;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        FMResultSet* set = nil;
        if (locationId) {
            NSString* sql = @"SELECT * FROM 'assetCheck' WHERE locationId =? ORDER BY createTime desc LIMIT ?";
            set = [db executeQuery:sql,@(locationId),@(showCount)];
        }else{
            NSString* sql = [NSString stringWithFormat:@"SELECT * FROM 'assetCheck' ORDER BY createTime desc  LIMIT %ld;", (long)showCount];
            set = [db executeQuery:sql];
        }
        //按照时间排序后，分时间段显示，构建二维数组
        NSString *lastDate = nil;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWAssetCheckRecord * assetCheckRecord = [self assetCheckRecordWithFMResultSet:set FMDatabase:db];
            NSString *timeDate = [YWCommonTool showChineseFormatterDate:assetCheckRecord.createTime/1000];
            if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                lastDate = timeDate;
                array = [NSMutableArray array];
            }
            [array addObject:assetCheckRecord];
            if (![blockAssetArray containsObject:array] && array.count) {
                [blockAssetArray addObject:array];
            }
        }
        [db closeOpenResultSets];
    }];
    return blockAssetArray.count ? blockAssetArray : nil;
}

- (YWAssetCheckRecord*)assetCheckRecordWithFMResultSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db
{
    YWAssetCheckRecord * assetCheckRecord = [[YWAssetCheckRecord alloc] init];
    assetCheckRecord.checkRecordId = [set intForColumn:@"checkRecordId"];
    NSString * buildingId = [set stringForColumn:@"buildingId"];
    NSString* sql = @"SELECT * FROM 'building' where buildingId=?;";
    FMResultSet* newSet = [db executeQuery:sql, buildingId];
    if ([newSet next]) {
        assetCheckRecord.building = [[YWDBTool shareDBTool] buildingWithSet:newSet];
    }
    NSInteger apartmentId = [set intForColumn:@"apartmentId"];
    sql = @"SELECT * FROM 'apartment' where apartmentId=?;";
    newSet = [db executeQuery:sql, @(apartmentId)];
    if ([newSet next]) {
        assetCheckRecord.apartment = [[YWDBTool shareDBTool] apartmentWithFMResultSet:newSet];
    }
    NSInteger floorId = [set intForColumn:@"floorId"];
    sql = @"SELECT * FROM 'floor' where floorId=?;";
    newSet = [db executeQuery:sql, @(floorId)];
    if ([newSet next]) {
        assetCheckRecord.floor = [[YWDBTool shareDBTool] floorWithFMResultSet:newSet];
    }
    NSInteger locationId = [set intForColumn:@"locationId"];
    sql = @"SELECT * FROM 'location' where locationId=?;";
    newSet = [db executeQuery:sql, @(locationId)];
    if ([newSet next]) {
        assetCheckRecord.location = [[YWDBTool shareDBTool] locationWithFMResultSet:newSet];
    }
    
    assetCheckRecord.createTime = [set longLongIntForColumn:@"createTime"];
    assetCheckRecord.updateTime = [set longLongIntForColumn:@"updateTime"];
    
    NSInteger creatorId = [set intForColumn:@"creatorId"];
    NSString* authorsql = @"SELECT * FROM 'handler' WHERE uniqueId =?;";
    FMResultSet* authorSet = [db executeQuery:authorsql, @(creatorId)];
    if ([authorSet next]) {
        assetCheckRecord.creator = [[YWDBTool shareDBTool] handlerWithSet:authorSet];
    }
    assetCheckRecord.checkResult = [set intForColumn:@"checkResult"];
    assetCheckRecord.note = [set stringForColumn:@"note"];
    assetCheckRecord.status = [set intForColumn:@"status"];
    
    NSMutableArray* detailArray = [NSMutableArray array];
    sql = @"SELECT * FROM 'assetCheckDetail' WHERE checkRecordId =?;";
    FMResultSet* detailSet = [db executeQuery:sql, @(assetCheckRecord.checkRecordId)];
    while ([detailSet next]) {
        YWAssetCheckRecordDetails* assetCheckDetail = [self assetCheckRecordDetailWithFMResultSet:detailSet FMDatabase:db];
        [detailArray addObject:assetCheckDetail];
    }
    assetCheckRecord.recordDetails = detailArray;
    return assetCheckRecord;
}

- (YWAssetCheckRecord*)assetCheckRecordWithCheckRecordId:(NSInteger)checkRecordId
{
    __block YWAssetCheckRecord* assetCheckRecord = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'assetCheck' WHERE checkRecordId = ? ;";
        FMResultSet* set = [db executeQuery:sql, @(checkRecordId)];
        if ([set next]) {
            assetCheckRecord = [self assetCheckRecordWithFMResultSet:set FMDatabase:db];
        }
        [db closeOpenResultSets];
    }];
    return assetCheckRecord;
}

#pragma mark - 资产清点明细表的更新、取值

- (BOOL)createAssetCheckDetailTable{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'assetCheckDetail' (checkRecordId integer,detailId integer,equipmentTypeId integer,referQuantity integer,checkQuantity integer,result integer);";
    return [[self fmdb] executeUpdate:sql];
}

- (BOOL)updateAssetCheckDetailWithArray:(NSArray*)checkDetailArray
{
    if (checkDetailArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockCheckDetailArray = checkDetailArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockCheckDetailArray enumerateObjectsUsingBlock:^(YWAssetCheckRecordDetails* _Nonnull checkRecordDetail, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'assetCheckDetail' WHERE detailId=?;";
            FMResultSet* set = [db executeQuery:sql, @(checkRecordDetail.detailId)];
            if ([set next]) {
                sql = @"UPDATE 'assetCheckDetail' SET equipmentTypeId =?,referQuantity =?,checkQuantity =?,result =?,checkRecordId =? WHERE detailId =?;";
                executeResult = [db executeUpdate:sql,@(checkRecordDetail.equipmentType.equipmentTypeId),@(checkRecordDetail.referQuantity),@(checkRecordDetail.checkQuantity),@(checkRecordDetail.result),@(checkRecordDetail.checkRecordId),@(checkRecordDetail.detailId)];
            }else {
                sql = @"INSERT INTO 'assetCheckDetail' (detailId,checkRecordId,equipmentTypeId,referQuantity,checkQuantity,result) VALUES (?, ?, ?, ?, ? ,?);";
                executeResult = [db executeUpdate:sql,@(checkRecordDetail.detailId),@(checkRecordDetail.checkRecordId),@(checkRecordDetail.equipmentType.equipmentTypeId),@(checkRecordDetail.referQuantity),@(checkRecordDetail.checkQuantity),@(checkRecordDetail.result)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (YWAssetCheckRecordDetails*)assetCheckRecordDetailWithFMResultSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db
{
    YWAssetCheckRecordDetails * assetCheckDetail = [[YWAssetCheckRecordDetails alloc] init];
    assetCheckDetail.detailId = [set intForColumn:@"detailId"];
    assetCheckDetail.checkRecordId = [set intForColumn:@"checkRecordId"];
    NSInteger equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
    
    NSString* sql = @"SELECT * FROM 'dict_equipment_type' where equipmentTypeId=?;";
    FMResultSet* newSet = [db executeQuery:sql, @(equipmentTypeId)];
    if ([newSet next]) {
        assetCheckDetail.equipmentType = [[YWDBTool shareDBTool] equipmentTypeWithFMResultSet:newSet db:db];
    }
    assetCheckDetail.referQuantity = [set intForColumn:@"referQuantity"];
    assetCheckDetail.checkQuantity = [set intForColumn:@"checkQuantity"];
    assetCheckDetail.result = [set intForColumn:@"result"];
    return assetCheckDetail;
}

@end
